/** 
 * https://leetcode.cn/problems/find-k-closest-elements/submissions/560558836/
 * 658. 找到 K 个最接近的元素
 * medium,  2024.9.2
 * 滑动窗口
 */
 
 class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        if (x <= arr[0]) {
            return vector<int>(arr.begin(), arr.begin()+k);
        }
        if (x >= arr.back()) {
            return vector<int>(arr.end()-k, arr.end());
        }
        int begin=0;
        int end=arr.size()-1;
        while (end-begin+1>k) {
            int left=x-arr[begin];
            int right=arr[end]-x;
            if (left<=right) {
                end--;
            } else {
                begin++;
            }
        }
        return vector<int>(arr.begin()+begin, arr.begin()+end+1);
    }
};